#!/usr/bin/env python

# 导入必要的模块
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import OVSKernelSwitch, RemoteController
from mininet.cli import CLI
from mininet.link import TCLink
from mininet.log import setLogLevel
import os


def create_vxlan_topology():
    net = Mininet(controller=RemoteController, switch=OVSKernelSwitch)

    # 添加控制器
    c0 = net.addController('c0', controller=RemoteController, ip='127.0.0.1', port=6633)

    # 创建3台交换机（VTEP）
    s1 = net.addSwitch('s1', dpid='1',ip='192.168.1.1')
    s2 = net.addSwitch('s2', dpid='2',ip='192.168.1.2')
    s3 = net.addSwitch('s3', dpid='3',ip='192.168.1.3')

    # # 添加主机
    # # 租户A（VNI 100）
    # h1 = net.addHost('h1', ip='10.1.1.1/24', mac='00:00:00:00:01:01')
    # h2 = net.addHost('h2', ip='10.1.1.2/24', mac='00:00:00:00:01:02')
    # # 租户B（VNI 200）
    # h3 = net.addHost('h3', ip='10.2.2.1/24', mac='00:00:00:00:02:01')
    # h4 = net.addHost('h4', ip='10.2.2.2/24', mac='00:00:00:00:02:02')

    # 构建Underlay网络
    net.addLink(s1, s2, bw=10, delay='5ms',port1=12,port2=21)
    net.addLink(s2, s3, bw=10, delay='10ms',port1=23,port2=32)
    net.addLink(s1, s3, bw=10, delay='15ms',port1=14,port2=34)

    # 连接主机
    # net.addLink(s1, h1, port1=11)
    # net.addLink(s3, h2, port1=31)
    # net.addLink(s1, h3, port1=13)
    # net.addLink(s3, h4, port1=33)

    # 启动网络
    net.build()
    c0.start()
    s1.start([c0])
    s2.start([c0])
    s3.start([c0])

    # 配置VXLAN隧道
    # s1.cmd('ovs-vsctl add-port s1 vxlan100 -- set interface vxlan100 type=vxlan options:remote_ip=127.0.0.1 options:key=100')
    # s1.cmd('ovs-vsctl add-port s1 vxlan200 -- set interface vxlan200 type=vxlan options:remote_ip=127.0.0.1 options:key=200')
    # s3.cmd('ovs-vsctl add-port s3 vxlan100 -- set interface vxlan100 type=vxlan options:remote_ip=127.0.0.1 options:key=100')
    # s3.cmd('ovs-vsctl add-port s3 vxlan200 -- set interface vxlan200 type=vxlan options:remote_ip=127.0.0.1 options:key=200')

    # 进入 CLI 模式
    CLI(net)

    # 停止网络
    net.stop()

if __name__ == '__main__':
    setLogLevel('info')
    create_vxlan_topology()